<style lang="less">
    @import './own-space.less';
</style>

<template>
    <div>
        <Card>
            <p slot="title">
                <Icon type="person"></Icon>
                个人信息
            </p>
            <div>
                <Form 
                    ref="userForm"
                    :model="userForm" 
                    :label-width="100" 
                    label-position="right"
                    :rules="inforValidate"
                >
                    <FormItem label="头像设置：">
                        <div style="display:inline-block;width:300px;">
                            <Row>
                                <div class="admin-upload-list" v-for="item in uploadList" :key="item.url">
                                    <template v-if="item.status === 'finished'">
                                        <img :src="item.url">
                                        <div class="admin-upload-list-cover">
                                            <Icon type="ios-eye-outline" @click.native="showImg = true"></Icon>
                                            <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <Spin fix v-if="item.showProgress">
                                            <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
                                        </Spin>
                                    </template>
                                </div>
                                <Upload
                                        ref="upload"
                                        name="file"
                                        :action="SERVER_HOST + 'upload/uploadFile'"
                                        :format="['jpg', 'png', 'jpeg', 'gif', 'bmp', 'svg']"
                                        :max-size="2048"
                                        :on-exceeded-size="handleMaxSize"
                                        :on-format-error="handleFormatError"
                                        :on-success="handleSuccess"
                                        :before-upload="handleBeforeUpload"
                                        type="drag"
                                        :show-upload-list="false"
                                        style="display: inline-block;width:58px;"
                                >
                                    <div style="width: 58px;height:58px;line-height: 58px;">
                                        <Icon type="camera" size="20"></Icon>
                                    </div>
                                </Upload>
                            </Row>
                        </div>
                    </FormItem>
                    <FormItem label="用户姓名：" prop="name">
                        <div style="display:inline-block;width:300px;">
                            <Input v-model="userForm.name" ></Input>
                        </div>
                    </FormItem>
                    <FormItem label="用户手机：" prop="cellphone" >
                        <div style="display:inline-block;width:204px;">
                            <Input v-model="userForm.cellphone" @on-keydown="hasChangePhone"></Input>
                        </div>
                        <div style="display:inline-block;position:relative;">
                            <Button @click="getIdentifyCode" :disabled="canGetIdentifyCode">{{ gettingIdentifyCodeBtnContent }}</Button>
                            <div class="own-space-input-identifycode-con" v-if="inputCodeVisible">
                                <div style="background-color:white;z-index:110;margin:10px;">
                                    <Input v-model="securityCode" placeholder="请填写短信验证码" ></Input>
                                    <div style="margin-top:10px;text-align:right">
                                        <Button type="ghost" @click="cancelInputCodeBox">取消</Button>
                                        <Button type="primary" @click="submitCode" :loading="checkIdentifyCodeLoading">确定</Button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </FormItem>
                    <FormItem label="登录密码：">
                        <Button type="text" size="small" @click="showEditPassword">修改密码</Button>
                    </FormItem>
                    <div>
                        <Button type="text" style="width: 100px;" @click="cancelEditUserInfor">取消</Button>
                        <Button type="primary" style="width: 100px;" :loading="save_loading" @click="saveEdit" :disabled="butSave">保存</Button>
                    </div>
                </Form>
            </div>
        </Card>
        <Modal v-model="editPasswordModal" :closable='false' :mask-closable=false :width="500">
            <h3 slot="header" style="color:#2D8CF0">修改密码</h3>
            <Form ref="editPasswordForm" :model="editPasswordForm" :label-width="100" label-position="right" :rules="passwordValidate">
                <FormItem label="原密码" prop="oldPass" :error="oldPassError">
                    <Input type="password" v-model="editPasswordForm.oldPass" placeholder="请输入现在使用的密码"></Input>
                </FormItem>
                <FormItem label="新密码" prop="newPass">
                    <Input type="password" v-model="editPasswordForm.newPass" placeholder="请输入新密码，至少6位字符" ></Input>
                </FormItem>
                <FormItem label="确认新密码" prop="rePass">
                    <Input type="password" v-model="editPasswordForm.rePass" placeholder="请再次输入新密码" ></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelEditPass">取消</Button>
                <Button type="primary" :loading="savePassLoading" @click="saveEditPass" >保存</Button>
            </div>
        </Modal>
        <Modal v-model="showImg" title="查看图片" @on-cancel="showImg = false">
            <img :src="imgUrl" width="100%" height="100%">
            <div slot="footer">
                <Button type="primary" @click="showImg = false">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import Cookies from 'js-cookie';
import util from '@/libs/util';
import CONSTANTS from '@/config/constants';

export default {
    name: 'ownspace_index',
    data () {
        const validePhone = (rule, value, callback) => {
            var re = /^1[0-9]{10}$/;
            if (!re.test(value)) {
                callback(new Error('请输入正确格式的手机号'));
            } else {
                callback();
            }
        };
        const valideRePassword = (rule, value, callback) => {
            if (value !== this.editPasswordForm.newPass) {
                callback(new Error('两次输入密码不一致'));
            } else {
                callback();
            }
        };
        return {
            baseuser: JSON.parse(Cookies.get('baseUser')),
            userForm: {
                name: '',
                cellphone: ''
            },
            uid: '', // 登录用户的userId
            securityCode: '', // 验证码
            phoneHasChanged: false, // 是否编辑了手机
            save_loading: false,
            identifyError: '', // 验证码错误
            editPasswordModal: false, // 修改密码模态框显示
            savePassLoading: false,
            oldPassError: '',
            identifyCodeRight: false, // 验证码是否正确
            hasGetIdentifyCode: false, // 是否点了获取验证码
            canGetIdentifyCode: false, // 是否可点获取验证码
            checkIdentifyCodeLoading: false,
            inforValidate: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                cellphone: [
                    { required: true, message: '请输入手机号码' },
                    { validator: validePhone }
                ]
            },
            editPasswordForm: {
                oldPass: '',
                newPass: '',
                rePass: ''
            },
            passwordValidate: {
                oldPass: [
                    { required: true, message: '请输入原密码', trigger: 'blur' }
                ],
                newPass: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, message: '请至少输入6个字符', trigger: 'blur' },
                    { max: 32, message: '最多输入32个字符', trigger: 'blur' }
                ],
                rePass: [
                    { required: true, message: '请再次输入新密码', trigger: 'blur' },
                    { validator: valideRePassword, trigger: 'blur' }
                ]
            },
            inputCodeVisible: false, // 显示填写验证码box
            initPhone: '',
            gettingIdentifyCodeBtnContent: '获取验证码', // “获取验证码”按钮的文字
            uploadList: [],
            SERVER_HOST: CONSTANTS.SERVER_HOST,
            showImg: false,
            imgUrl: '',
            butSave: false
        };
    },
    methods: {
        getIdentifyCode () {
            this.hasGetIdentifyCode = true;
            this.$refs['userForm'].validate((valid) => {
                if (valid) {
                    this.canGetIdentifyCode = true;
                    let timeLast = 60;
                    let timer = setInterval(() => {
                        if (timeLast >= 0) {
                            this.gettingIdentifyCodeBtnContent = timeLast + '秒后重试';
                            timeLast -= 1;
                        } else {
                            clearInterval(timer);
                            this.gettingIdentifyCodeBtnContent = '获取验证码';
                            this.canGetIdentifyCode = false;
                        }
                    }, 1000);
                    this.inputCodeVisible = true;
                    // you can write ajax request here
                }
            });
        },
        showEditPassword () {
            this.editPasswordForm = {};
            this.editPasswordModal = true;
        },
        cancelEditUserInfor () {
            this.$store.commit('removeTag', 'ownspace_index');
            localStorage.pageOpenedList = JSON.stringify(this.$store.state.app.pageOpenedList);
            let lastPageName = '';
            if (this.$store.state.app.pageOpenedList.length > 1) {
                lastPageName = this.$store.state.app.pageOpenedList[1].name;
            } else {
                lastPageName = this.$store.state.app.pageOpenedList[0].name;
            }
            this.$router.push({
                name: lastPageName
            });
        },
        saveEdit () {
            this.$refs['userForm'].validate((valid) => {
                if (valid) {
                    if (this.phoneHasChanged && this.userForm.cellphone !== this.initPhone) { // 手机号码修改过了而且修改之后的手机号和原来的不一样
                        if (this.hasGetIdentifyCode) { // 判断是否点了获取验证码
                            if (this.identifyCodeRight) { // 判断验证码是否正确
                                this.saveInfoAjax();
                            } else {
                                this.$Message.error('验证码错误，请重新输入');
                            }
                        } else {
                            this.$Message.warning('请先点击获取验证码');
                        }
                    } else {
                        this.saveInfoAjax();
                    }
                }
            });
        },
        cancelEditPass () {
            this.editPasswordModal = false;
        },
        saveEditPass () {
            this.$refs['editPasswordForm'].validate((valid) => {
                if (valid) {
                    let formData = {};
                    for (let key in this.baseuser) {
                        formData[key] = this.baseuser[key];
                    }
                    formData.password = this.editPasswordForm.newPass === '' ? formData.password : this.editPasswordForm.newPass;
                    this.savePassLoading = true;
                    // you can write ajax request here
                    util.ajax.post('/base/user/login', util.toFormData({
                        login: this.baseuser.loginid,
                        password: this.editPasswordForm.oldPass
                    })).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            util.ajax.post('/base/user/save', util.toFormData(formData)).then(res => {
                                if (res.data.message === 'SUCCESS') {
                                    this.$Message.success('保存成功');
                                    this.savePassLoading = false;
                                    this.editPasswordModal = false;
                                    this.baseuser = formData;
                                }
                            });
                        } else {
                            this.$Modal.error({
                                content: '原密码错误请重新输入'
                            })
                            this.savePassLoading = false;
                        }
                    });
                }
            });
        },
        init () {
            this.userForm.name = this.baseuser.name;
            this.userForm.cellphone = this.baseuser.phone;
            this.initPhone = this.baseuser.phone;
            if (this.baseuser.headurl) {
                this.$refs.upload.fileList = [];
                this.uploadList = [{
                    status: 'finished',
                    showProgress: true,
                    url: this.SERVER_HOST + this.baseuser.headurl
                }];
                this.imgUrl = this.SERVER_HOST + this.baseuser.headurl;
            } else {
                this.uploadList = this.$refs.upload.fileList = [];
            }
        },
        cancelInputCodeBox () {
            this.inputCodeVisible = false;
            this.userForm.cellphone = this.initPhone;
        },
        submitCode () {
            let vm = this;
            vm.checkIdentifyCodeLoading = true;
            if (this.securityCode.length === 0) {
                this.$Message.error('请填写短信验证码');
            } else {
                setTimeout(() => {
                    this.$Message.success('验证码正确');
                    this.inputCodeVisible = false;
                    this.checkIdentifyCodeLoading = false;
                }, 1000);
            }
        },
        hasChangePhone () {
            this.phoneHasChanged = true;
            this.hasGetIdentifyCode = false;
            this.identifyCodeRight = false;
        },
        saveInfoAjax () {
            this.save_loading = true;
            let formData = {};
            for (let key in this.baseuser) {
                formData[key] = this.baseuser[key];
            }
            formData.name = this.userForm.name;
            formData.phone = this.userForm.cellphone;
            formData.headurl = this.userForm.headurl ? this.userForm.headurl : '';
            util.ajax.post('/base/user/save', util.toFormData(formData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.$Message.success('修改成功，保存内容时下次登录生效！');
                    this.save_loading = false;
                    this.baseuser = formData;
                }
            });
        },
        handleSuccess (res, file) {
            this.uploadList = [{
                showProgress: true
            }]
            var xmlhttp = null;
            var urlPath = CONSTANTS.SERVER_HOST + res.data.imgUrl;
            if (window.ActiveXObject) {
                xmlhttp = new ActiveXObject("Microsoft.XMLDOM");
            } else {
                if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                }
            }
            this.butSave = true;
            let interval = setInterval(() => {
                xmlhttp.open('GET', urlPath, false);
                xmlhttp.send();
                if ((xmlhttp.readyState === 4 && xmlhttp.status === 200)) {
                    clearInterval(interval);
                    this.$Notice.success({
                        title: '文件上传成功',
                        desc: '文件 ' + file.name + ' 上传成功。',
                        duration: 2
                    });
                    file.url = CONSTANTS.SERVER_HOST + res.data.imgUrl;
                    file.name = res.data.fileName;
                    this.uploadList = this.$refs.upload.fileList;
                    this.userForm.headurl = res.data.imgUrl;
                    this.imgUrl = CONSTANTS.SERVER_HOST + res.data.imgUrl;
                    this.butSave = false;
                }
            }, 500);
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请选择图片文件。',
                duration: 5
            });
            this.butSave = false;
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。',
                duration: 5
            });
            this.butSave = false;
        },
        handleRemove (file) {
            this.uploadList = [];
            this.$refs.upload.fileList = [];
            this.userForm.headurl = '';
            this.butSave = false;
        },
        handleBeforeUpload () {
            const check = this.uploadList.length < 1;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 1 张图片。',
                    duration: 5
                });
            }
            this.butSave = false;
            return check;
        }
    },
    mounted () {
        this.init();
    }
};
</script>
